
require_relative 'permission_roles'
require_relative 'user'
require_relative 'triggers'
require_relative 'pre_build'
require_relative 'post_build'
require_relative 'xml_helpers'
require_relative 'command'

module CSDNConfig

	# represents a single Jenkins job. 
	# Call to_xml to return the config for uploading to Jenkins.
	class Job
		attr_reader :name
		attr_accessor :description
		attr_accessor :users
		attr_accessor :repo_name
		attr_accessor :repo_group
	    attr_accessor :local_source_dir
		attr_accessor :command # set of commands used to build the job
		attr_accessor :node_tags
		attr_accessor :enabled
		attr_accessor :triggers
	    attr_accessor :pre_build
		attr_accessor :post_build

		include XMLHelpers

		def initialize(name)
	      Job.all_jobs << self

			@name = name
			@users = PermissionRoles.new
			# disable the tags currently
			#@node_tags = %w{gitlab maven ruby}
			@node_tags = %w{master}
			@enabled = true
			@local_source_dir = 'src'
			@repo_name = name
			@repo_group = 'CSDN_Dev'
			@triggers = []
			@pre_build = []
			@post_build = []
		end

		# add downstream projects
		def add_child(*children)
			Job.dependencies[name] += [*children].flatten
		end

		alias_method :add_children, :add_child

		# add upstream projects
		def add_dependency(*parents)
			[*parents].flatten.each do |parent|
				Job.dependencies[parent] << self.name
			end
		end

		alias_method :add_dependencies, :add_dependency

		def children
			Job.dependencies[name]
		end

		def add_notification(*users)
		  @users.add_user(*users)
		end

		def add_permission(user,role=:builder)
		  @users.add_permission(user,role)
		end

		def disable
			@enabled = false
		end

		def disabled_string
			@enabled ? 'false' : 'true'
		end

		def validate!
			raise "No users added to job #{name}!" if @users.empty?
			raise "command not given for job #{name}!" if command.nil?
		end

		def to_xml
			validate!
			apply_template :job
		end

		def self.all_jobs
		  @allJobs ||= []
		end

		def self.dependencies
			@jobDependencies ||= Hash.new {|h,k| h[k] = Array.new}
		end

	end

end

if __FILE__ == $0
	testJob = CSDNConfig::Job.new('test')

	cmd = CSDNConfig::Command.new
	cmd.standard_build_setup
	cmd.clean_build_directory 'build'
	cmd.make
	cmd.cd '..'
	cmd.gcovr_coverage_report 'src', 'build'

	testJob.command = cmd
	testJob.users.add 'core'
	testJob.triggers << CSDNConfig::Triggers::SCM.frequently
	puts testJob.to_xml
end
